package sights.scenic_detail.servlet;

import com.alibaba.fastjson.JSONObject;
import sights.VO.ScenicDetailVO;
import sights.scenic_detail.service.DetailService;
import sights.scenic_detail.service.DetailServiceImpl;
import util.PageModel;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(value = "*.detail")
public class DetailServlet extends HttpServlet {
    private DetailService detailService=new DetailServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath=req.getServletPath();
        switch (servletPath){
            case "/toDetail.detail":
                toDetail(req,resp);
                break;
            case"/selectById.detail":
                selectById(req,resp);
                break;
            default:
                break;
        }
    }
    public void toDetail(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/detail.html").forward(req,resp);
    }
    public void selectById(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer=resp.getWriter();
        try {
            String id = req.getParameter("sight_id");
            // 简单校验参数是否为空
            if (id == null || id.trim().isEmpty()) {
                writer.print("{\"error\":\"景点ID不能为空\"}");
                return;
            }
            // 捕获数字转换异常
            Integer sight_id = Integer.valueOf(id);
            ScenicDetailVO vo = detailService.selectById(sight_id);
            String jsonStr = JSONObject.toJSONString(vo);
            writer.print(jsonStr);
        } catch (NumberFormatException e) {
            // 处理非数字参数的情况
            writer.print("{\"error\":\"景点ID必须是数字\"}");
        } finally {
            writer.close();
        }
    }
}
